// index.js
// 获取应用实例
const app = getApp()
Page({
    data: {
        userInfo: {},
        hasUserInfo: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        hasAreaNum:app.globalData.hasAreaNum,
        isEdit:true,//是否给修改入口
        isForbidden:true,//是否给启用入口
        userId:'',//修改或新增页面加载和更新数据时 必带参数-用户id
        userPhone:'',//当前新增授权 但用户未绑定时传入参数
        authorizeId:'',///修改授权时回传idF
        tel:'',//手机号
        clientName:'',//当前授权区域
        clientIndex:2,//当前授权区域对应索引
        clientCode:'',//当前区域对应areaCode
        clientArray:{
            clientName:[],
            clientCode:[]
        },//所有区域列表
        authorizeTypeArray: ['单次授权', '永久授权', '临时授权'],//所有授权数据
        authorizeTypeIndex: 1,//当前授权对应code
        authorizeType:'单次授权',//当前授权类型
        authorizeStartTime:'2018-06-25 18:18',//授权开始时间
        authorizeEndTime:'2018-06-25 18:18',//授权结束时间
        //授权区域
        checkboxItems: [
            // {name: '客厅', value: '0',areaIds:'1', checked: true},
            // {name: '餐厅', value: '1',areaIds:'2',checked:true},
            // {name: '厨房', value: '2',areaIds:'3'},
            // {name: '主卧', value: '3',areaIds:'4'},
            // {name: '次卧', value: '4',areaIds:'5'},
            // {name: '洗手间', value: '5',areaIds:'6'}
        ],
        resendCode:{//重新发送授权码
            sec:60,
            secText:'',
            isClick:true, //true 允许点击 false 禁止点击
        }
    },
    onLoad: function (option) {
        // 调用应用实例的方法获取全局数据
        let app = getApp();
        // toast组件实例
        new app.ToastPannel();
        var that = this;
        if (app.globalData.userInfo) {
            this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
            })
        } else if (this.data.canIUse){
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.userInfoReadyCallback = res => {
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
                success: res => {
                    app.globalData.userInfo = res.userInfo;
                    this.setData({
                        userInfo: res.userInfo,
                        hasUserInfo: true
                    })
                }
            })
        }

        this.setData({
            hasAreaNum:app.globalData.hasAreaNum //设置当前用户所有区域数量
        });
        app.globalData.detailClientCode = option.clientCode; //存储clientCode到全局字段 修改新增完成通过时回跳用户列表时调用
        app.globalData.thisOption = option;//存储option数据到公共字段 返回页面时调用
    },
    onShow:function(){
        var that = this;
        var option = app.globalData.thisOption;
        //接受传入userId clientCode参数
        console.log(option)
        if(!option.userId || option.userId =='' || option.userId == undefined){// 判断userId是否存在
            var data = {userPhone:option.userPhone,clientCode:option.clientCode};
            this.setData({
                isEdit:false,//隐藏修改按钮
                userPhone:option.userPhone
            })
        }else {
            var data = {userId: option.userId, clientCode: option.clientCode};
            this.setData({
                isEdit: true,//显示修改按钮
                userId: option.userId,
                clientCode: option.clientCode
            })
        }
        if(option.forbidden == '2'){//判断是否为禁用状态
            that.setData({
                isForbidden:true
            })
        }else{
            that.setData({
                isForbidden:false
            })
        }
        //显示加载中
        wx.showLoading({title:'加载中'});//
        wx.request({
            url: app.globalData.globalApi + "bisUserAuthorizationRecord/queryBisUserAuthorizationRecordById",//获取授权详情
            data:data,
            method: 'get', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            // dataType: 'json',
            header: {
                "token-session": app.globalData.tokenSession, // 设置请求的header，写入返回token
                'experience-Pattern':app.globalData.experiencePattern// 是否为体验用户
            },
            success: function (res) {
                //隐藏加载中
                wx.hideLoading({title:'加载中'});
                var resData = res.data;
                if (resData.success == true && resData.data && resData.code == 0) {
                    const data = resData.data;
                    const length = data.length;
                    const authData = [];//组装数据预设
                    const authorizeId = data.id;
                    const tel = data.toUserMobile;//手机号
                    const clientName = data.clientName;//区域名
                    const clientCode = data.clientCode;//区域代码
                    const authorizeTypeIndex= data.authorizedType-1;//当前授权对应code
                    const authorizeType=that.data.authorizeTypeArray[authorizeTypeIndex];//当前授权类型
                    const startMillisecond=data.authorizedBeginTime;//开始毫秒数
                    const endMillisecond=data.authorizedEndTime;//结束毫秒数
                    const authorizeStartTime=that.getDateFuc(startMillisecond);//授权开始时间
                    const authorizeEndTime=that.getDateFuc(endMillisecond);//授权结束时间
                    const checkboxItems=[];
                    for (let i = 0; i < data.bisAreaDtoList.length; i++) {//组装区域数据
                        // console.log(data.bisAreaDtoList[i]);
                        checkboxItems.push({name:data.bisAreaDtoList[i].areaName,value:i,areaIds:data.bisAreaDtoList[i].areaCode,checked:data.bisAreaDtoList[i].flagUserArea})
                    }
                    that.setData({
                        authorizeId:authorizeId,
                        tel:tel,
                        clientName:clientName,
                        clientCode:clientCode,
                        authorizeTypeIndex:authorizeTypeIndex,
                        authorizeType:authorizeType,
                        authorizeStartTime:authorizeStartTime,
                        startMillisecond:startMillisecond,
                        authorizeEndTime:authorizeEndTime,
                        endMillisecond:endMillisecond,
                        checkboxItems:checkboxItems
                    });
                } else {

                }
            }
        })

    },
    getDateFuc:function(data){//时间戳转日期函数
        var data = data;
        var unixTimestamp = new Date(data);
        return unixTimestamp.getFullYear() + "年" + (unixTimestamp.getMonth() + 1) + "月" + unixTimestamp.getDate() + "日 " + unixTimestamp.getHours() + "时"
    },
    getUserInfo: function(e) {
        console.log(e);
        app.globalData.userInfo = e.detail.userInfo;
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    editAuthorizeFuc:function(){//跳转修改页面
        var that = this;
        var userId = that.data.userId;
        var clientCode = that.data.clientCode;
        app.globalData.authorizeData = false; //设置为ture 判断为进入修改授权页面
        wx.navigateTo({
            url: '../settingAuthorizeAddEdit/settingAuthorizeAddEdit?userId='+userId+"&&clientCode="+clientCode
        })
    },
    forbiddenFuc:function () {// 禁用授权
        var that = this;
        var authorizeId = that.data.authorizeId;
        wx.request({
            url: app.globalData.globalApi + "bisUserAuthorizationRecord/updateBisUserAuthorizationRecordById",//获取设置用户配置接口
            data:{
                id:authorizeId
            },
            method: 'get', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            dataType: 'json',
            header: {
                "token-session": app.globalData.tokenSession, // 设置请求的header，写入返回token
                'experience-Pattern':app.globalData.experiencePattern// 是否为体验用户
            },
            success: function (res) {
                console.log(res);
                var data = res.data;
                var url = '../settingAuthorizeView/settingAuthorizeView?clientCode='+app.globalData.detailClientCode;
                if (data.success==true && data.code==0){
                    that.show(data.msg,'success','',url);//弹出提示信息
                } else{
                    that.show(data.msg,'failed','',url);//弹出提示信息
                }
            }
        });
    },
    openFuc:function () {//启用授权
        var that = this;
        // authorizeTypeIndex: 1,//当前授权对应code
        //     authorizeType:'单次授权',//当前授权类型
        //     authorizeStartTime:'2018-06-25 18:18',//授权开始时间
        //     authorizeEndTime:'2018-06-25 18:18',//授权结束时间
        var toData = {
            id:that.data.authorizeId,// 和禁用的是一样的,
            authorizedType:that.data.authorizeTypeIndex + 1,// 类型,
            authorizedBeginTime:that.data.startMillisecond,  // 开始时间,
            authorizedEndTime:that.data.endMillisecond// 结束时间
        };
        wx.request({
            url: app.globalData.globalApi + "bisUserAuthorizationRecord/updateBisUserAuthEnable",//获取设置用户配置接口
            data:toData,
            method: 'post', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            dataType: 'json',
            header: {
                "token-session": app.globalData.tokenSession, // 设置请求的header，写入返回token
                'experience-Pattern':app.globalData.experiencePattern// 是否为体验用户
            },
            success: function (res) {
                console.log(res);
                var data = res.data;
                var url = '../settingAuthorizeView/settingAuthorizeView?clientCode='+app.globalData.detailClientCode;
                if (data.success==true && data.code==0){
                    that.show(data.msg,'success','',url);//弹出提示信息
                } else{
                    that.show(data.msg,'failed','',url);//弹出提示信息
                }
            }
        });
    },
    resendCodeFuc:function () {//重发验证码
        var that = this;
        var authorizeId = that.data.authorizeId;
        if(that.data.resendCode.isChick===false){
            return false;
        }else{
            wx.showLoading();
        }
        wx.request({
            url: app.globalData.globalApi + "home/reSendMess?auth_id="+authorizeId,//重发验证码接口
            data: {},
            method: 'post', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            dataType: 'json',
            header: {
                "token-session": app.globalData.tokenSession, // 设置请求的header，写入返回token
                'experience-Pattern': app.globalData.experiencePattern// 是否为体验用户
            },
            success: function (res) {
                wx.hideLoading();
                if(res.data.code===0){
                    that.Countdown();
                    that.setData({
                        'resendCode.isChick':false,
                    })
                }else{
                    that.show(res.data.msg,'failed','')
                }
            }
        });
    },
    Countdown:function () {//授权码一分钟倒计时
        var that = this;
        var sec = that.data.resendCode.sec;
        if(sec<0){
            that.setData({
                'resendCode.isChick':true,
                'resendCode.secText':""
            });
            clearTimeout(timer);
        }else{
            that.setData({
                'resendCode.sec':sec-1,
                'resendCode.secText':"("+sec+")"
            });
            var timer = setTimeout(function () {
                that.Countdown();
            }, 1000);
        }


    },
    // onShow:function () {
    //     var that = this;
    //     that.onLoad();//重载数据
    // }
});